const common = require("../../common/common").common;

function IsAuthor(options) {
    let warrant = common.checkUserWarrant();
    //是否有用户信息
        let page = getCurrentPages().pop();
    console.log("授权弹窗组件");
    console.log(warrant);
    if (warrant) {
        //没有用户信息
        //判断是否授权
        wx.getSetting({
            success(res) {
                console.log(res);
                if (page.data.userAuditStatus == 1 || page.data.userAuditStatus == 3) {
                    //获取用户信息未授权，显示授权弹窗
                    const {selector: selector = "#authorization"} = options;
                    //选择器可自定义id
                    //获取id为toast的组件
                                        const ctx = getCtx(selector);
                    ctx.modalShow();
                    return false;
                } else {
                    //用户授权过，获取用户信息
                    if (options.success) {
                        options.success();
                    } else {
                        skipWay(options);
                    }
                }
            }
        });
    } else {
        //执行回调或者跳转连接
        if (options.success) {
            options.success();
        } else {
            skipWay(options);
        }
    }
}

/**
 * 获取组件
 */ function getCtx(selector) {
    const pages = getCurrentPages();
    //获取页面列表
        const ctx = pages[pages.length - 1];
    //当前页面
        const componentCtx = ctx.selectComponent(selector);
    //当前页面获取id为"toast"的组件
        if (!componentCtx) {
        return null;
    }
    return componentCtx;
}

/**
 * 跳转方法判断
 */ function skipWay(options) {
    if (options.url) {
        switch (options.skipWay) {
          case "navigateTo":
            wx.navigateTo({
                url: options.url
            });
            break;

          case "relaunchTo":
            wx.relaunchTo({
                url: options.url
            });
            break;

          case "redireactTo":
            wx.redireactTo({
                url: options.url
            });
            break;

          default:
            wx.navigateTo({
                url: options.url
            });
        }
    }
}

module.exports = {
    $author: IsAuthor
};